const { MapRoute } = require('./A star.js')
const { Canvas } = require('./draw.js')

var that, app
var canvas, ctx
var mapRoute
var info = {
  grid: {
    w: 24, // 地图水平方向格子数
    h: 40, // 地图垂直方向格子数
    obstacle : 20 / 100
  },
  map: {
    m: 10 // 地图边界宽度
  }
}
Page({

  // 页面的初始数据
  data: {
  },

  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    that = this
    app = getApp()
    if(options.info != undefined) info = JSON.parse(options.info)
    this.Running()
  },

  onShow: function (event){
    
  },

  Running: function () {
    if(mapRoute != undefined) mapRoute.stop()
    info.de = wx.getSystemInfoSync()
    info.map.width =  info.de.screenWidth - info.map.m
    info.map.linespace = (info.map.width - info.map.width % info.grid.w) / info.grid.w
    this.setData({
      width: info.de.screenWidth,
      height:info.map.linespace * info.grid.h + 10
    })

    var row=info.grid.h, col=info.grid.w
    var map2d = []
    var barrierlist = []
    for(var i = 0; i < row;i++){
      var newRow = []
      for(var j = 0; j< col; j++) newRow.push(0)
      map2d.push(newRow)
    }
    for(var i = 0; i < info.grid.h * info.grid.w * info.grid.obstacle; i ++ ){
      var x = Math.floor(Math.random() * info.grid.w) , y = Math.floor(Math.random() * info.grid.h)
      while((x == 0 && y == 0) || (x == info.grid.w - 1 && y == info.grid.h - 1) || map2d[y][x] == 1)
       x = Math.floor(Math.random() * info.grid.w) , y = Math.floor(Math.random() * info.grid.h)
      map2d[y][x] = 1
      barrierlist.push({x: x, y: y})
    }

    ctx = wx.createCanvasContext('canvas')
    canvas = new Canvas(ctx, info)
    canvas.draw(map2d, barrierlist)

    var start = [0,0], end = [info.grid.w - 1, info.grid.h -1 ]
    mapRoute = new MapRoute(start, end, map2d)
    mapRoute.begin(canvas, barrierlist)
  },

  setParameter: function () {
    wx.navigateTo({
      url: '/pages/para/para?info=' + JSON.stringify(info)
    })
  }
})